//
//  MyCustomSubVC.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/5/22.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "MyCustomSubVC.h"
#import "AcitonBayStyleTitleView.h"
#import "ScroDeleteTableView.h"
#import "config.h"
#import "NodataCell.h"
#import "RealCustomerCell.h"
#import "BrokerDataMange.h"
#import "UserModal.h"
#import "SearchView.h"

#import "MJRefresh.h"
#import "CustomerModel.h"
#import "LatentCustomerCCell.h"

#import "BingPremiseVc.h"
#import "MBProgressHUD+MJ.h"
#import "MiddleManAddCustomerViewController.h"
#import "MiddleManAddLatentCustomerViewController.h"
#import "MBProgressHUD+MJ.h"

#import "FooterMenuView.h"
#import "StringTool.h"
#import "EditRealCustomerVc.h"
#import "AddRealCustomerVC.h"
#import "HideTextVeiw.h"


@interface MyCustomSubVC ()<UITableViewDataSource,UITableViewDelegate,SearchViewDelegate,RealCustomerCellDelegate,LatentCustomerCCellDelegate,UITextFieldDelegate,FooterMenuViewDelegate,ScroDeleteTableViewDelgate>
@property (weak, nonatomic) IBOutlet UITextField *seachField;
@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (strong, nonatomic) ScroDeleteTableView *mainTableView;
@property (nonatomic,strong) SearchView *seachView;

@property (strong, nonatomic) NSArray *dataArray;
@property (strong, nonatomic) BrokerDataMange *dataMange;
@property (strong, nonatomic) NodataCell *nodataCell;
@property (assign, nonatomic) NSInteger pageIndex; //非搜索模式下的index
@property (nonatomic,assign)NSInteger searchIndex;//搜索模式下的index
@property(nonatomic,assign) NSInteger stateFlag;//=1真实客户，－1潜在客户

@property(nonatomic,strong)  NSMutableArray *seachArray;
@property (copy, nonatomic) NSString *keyWord;//搜索关键字
@property(nonatomic,assign) BOOL isSeachType;//是否是搜索的情况

@property (strong, nonatomic) FooterMenuView *footerView;
@property (nonatomic,assign) Boolean isEditMode;


@property(nonatomic,assign) Boolean isSeletedAll;//是否全选了，默认为false
@property(nonatomic,assign) NSInteger isClickAbleBtn;//默认为0 ，1点击了启用，－1点击了禁用

@property (weak, nonatomic) IBOutlet UIButton *cacelBtn;

@property (weak, nonatomic) IBOutlet HideTextVeiw *seacrTv;



@end

@implementation MyCustomSubVC
@synthesize actionTitleView,contentView,mainTableView,seachView,dataArray,nodataCell,pageIndex,state,seachArray,keyWord,isSeachType,footerView,isEditMode;


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self initView];
    
    if (!self.pageVC.titleViewClickLisIsAdd) {
        
        [[actionTitleView abackBtn]addTarget:self action:@selector(myCustomerVcBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [[actionTitleView aeditBtn]addTarget:self action:@selector(myCustomerVcBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [[actionTitleView aaddBtn]addTarget:self action:@selector(myCustomerVcBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        
        self.pageVC.titleViewClickLisIsAdd = true;
    }
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if (self.isEditMode ==true) {
        [self myCustomerVcBtnClicked:self.actionTitleView.aeditBtn];
    }
    
    [self.seacrTv resignFirstResponder ];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    
    if (self.state == CUSTOMER_TURE) {
        actionTitleView.aeditBtn.hidden = NO;
        actionTitleView.aaddBtn.tag = 100;
    }else if (self.state == CUSTOMER_LATENT)
    {
        actionTitleView.aaddBtn.tag = 200;
        actionTitleView.aeditBtn.hidden = YES;
    }
    
    
    [self refreshData];
}

-(BrokerDataMange *)dataMange
{
    if (!_dataMange) {
        _dataMange = [[BrokerDataMange alloc]init];
    }
    return _dataMange;
}
-(void)initView
{
    
    pageIndex = 1;
    self.searchIndex = 1;
    
    keyWord = @"";
    isSeachType = NO;
    [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
    self.cacelBtn.enabled = NO;
    
    [self.seachField setLeftViewMode:UITextFieldViewModeAlways];
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 38, 44)];
    
    UIImageView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(backView.frame.size.width/2-8, backView.frame.size.height/2-8, 15, 15)];
    [leftView setImage:[UIImage imageNamed:@"search_icom"]];
    [backView addSubview:leftView];
    [self.seachField setLeftView:backView];
    self.seachField.delegate =self;
    NSString *placeHodler = self.state == CUSTOMER_TURE?@"可通过客户姓名或手机号搜索":@"可通过客户姓名搜索";
    [self.seacrTv setHideText:placeHodler];
    
    self.seachField.placeholder = self.state == CUSTOMER_TURE?@"可通过客户姓名或手机号搜索":@"可通过客户姓名搜索";
    
    mainTableView = [[ScroDeleteTableView alloc]initWithFrame:CGRectMake(0, 0, PMW,PMH - 64 - 42 - 15 - 15)];
    [self.contentView addSubview:mainTableView];
    self.mainTableView.delegate =self;
    self.mainTableView.dataSource = self;
    mainTableView.menuStatedelegate = self;
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, PMW, 15)];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, headView.frame.size.height-1, headView.frame.size.width, 1)];
    [headView setBackgroundColor:UIColorFromRGB(0xf3f3f3)];
    [line setBackgroundColor:UIColorFromRGB(0xe3e3e3)];
    [headView addSubview:line];
    [self.mainTableView setTableHeaderView:headView];
    
    
    if (isIOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    if (isIOS7) {
        if ([self.mainTableView respondsToSelector:@selector(setSeparatorInset:)]) {
            [self.mainTableView setSeparatorInset:UIEdgeInsetsZero];
        }
    }
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    seachView = [[SearchView alloc]initWithParentView:self.mainTableView withEt:self.seachField];
    seachView.delegate = self;
    seachView.textView = self.seacrTv;
    [self.seachView.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(searchLoadMore)];
    
    [self.mainTableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    [self.mainTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    
    
    footerView = [FooterMenuView creatView];
    footerView.delegate = self;
    footerView.frame = CGRectMake(0, UIScreenHeight - 64-40-35, UIScreenWidth, 40);
    [self.view addSubview:footerView];
    [footerView setHidden:YES];
    [footerView.moveBtn setHidden:YES];
    footerView.beAbleBtn.enabled = YES;
    footerView.beUnAbleBtn.enabled = YES;
    
    
}

-(void)refreshData
{
    self.pageIndex = 1;
    [self loadMore];
}

-(void)searchRefreshData
{
    self.searchIndex = 1;
    [self searchLoadMore];
    
}

//请求数据（搜索情况）
-(void)searchLoadMore
{
    
    [self.seachView.tableView.footer resetNoMoreData];
    
    [seachView tableViewReloadAndUpFrame];
    
    __weak typeof(self)bself = self;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *resultMod=  [bself.dataMange refeshDataConsumerListWithCustomerId:[UserModal shareUserModel].userId WithPageIndex:self.searchIndex WithKeyWord:keyWord WithCustomerState: bself.state];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [seachView.tableView.footer endRefreshing];
            
            if (resultMod.resltState==ResultNetError) {
                
                [MBProgressHUD showError:@"网络错误"];
                
            }else if (resultMod.resltState==ResultFail){
                
                [MBProgressHUD showError:[NSString stringWithFormat:@"网络错误%@",resultMod.resultCode]];
                
            }else{
                
                NSArray *moreData = resultMod.dataMod;
                if (self.searchIndex == 1) {
                    bself.seachArray = [[NSMutableArray alloc]initWithArray:moreData];
                }else
                {
                    NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:bself.seachArray];
                    if (moreData.count == 0 || moreData == nil) {
                        [bself.seachView.tableView.footer noticeNoMoreData];
                    }
                    [arr addObjectsFromArray:moreData];
                    bself.seachArray = [[NSMutableArray alloc]initWithArray:arr];
                }
                if (moreData.count > 0) {
                    
                    self.searchIndex ++;
                }
                
            }
            [seachView tableViewReloadAndUpFrame];
        });
    });
    
}
//请求数据(非搜索模式下）
-(void)loadMore
{
    
    [self.mainTableView.footer resetNoMoreData];
    [mainTableView reloadData];
    [nodataCell setState:nodataCellStateLoading];
    __weak typeof(self)bself = self;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.keyWord = @"*";
        ResulteMod *resultMod=  [self.dataMange refeshDataConsumerListWithCustomerId:[UserModal shareUserModel].userId WithPageIndex:pageIndex WithKeyWord:keyWord WithCustomerState: bself.state];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [mainTableView.footer endRefreshing];
            [mainTableView.header endRefreshing];
            
            if (resultMod.resltState==ResultNetError) {
                
                [bself.nodataCell setState:nodataCellStateNetError];
                
            }else if (resultMod.resltState==ResultFail){
                
                [bself.nodataCell setCodeErrorTip:resultMod.resultCode];
                
            }else{
                
                NSArray *moreData = resultMod.dataMod;
                if (moreData.count > 0 && moreData != nil) {
                    if (pageIndex == 1) {
                        bself.dataArray = [[NSArray alloc]initWithArray:moreData];
                        
                    }else
                    {
                        
                        NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:bself.dataArray];
                        
                        [arr addObjectsFromArray:moreData];
                        bself.dataArray = [[NSArray alloc]initWithArray:arr];
                    }
                    pageIndex ++;
                    
                }else
                {
                    
                    if(pageIndex == 1)
                    {
                        bself.dataArray = nil;
                        [nodataCell setState:nodataCellStateNodata];
                    }else
                    {
                        [mainTableView.footer noticeNoMoreData];
                    }
                }
            }
            
            [mainTableView reloadData];
            
        });
    });
    
}

#pragma tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (dataArray&&dataArray.count>0) {
        [mainTableView setScrollEnabled:YES];
        return self.dataArray.count;
    }else{
        [self.mainTableView setContentOffset:CGPointMake(0, 0)];
        [self.mainTableView setScrollEnabled:NO];
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (dataArray.count==0) {
        if(!nodataCell){
            nodataCell = [[NodataCell alloc] initWithFrame:mainTableView.frame];
            [nodataCell setState:nodataCellStateLoading];
            [[nodataCell refreshBtn]setTag:56];
            [nodataCell.refreshBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
            
        }
        
        
        return nodataCell;
    }
    
    if (self.state == CUSTOMER_TURE) {//真实客户
        static NSString *ID = @"realCustomerCell";
        RealCustomerCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil)
        {
            cell = [[RealCustomerCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            
            [cell cellWithTableView:mainTableView];
        }
        
        cell.contentMoveView.tag = indexPath.row;
        [cell.contentMoveView addTarget:self action:@selector(cellOnClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.btnDelegate = self;
        
        CustomerModel *model = [dataArray objectAtIndex:indexPath.row];
        cell.model = model;
        cell.isEditMode = self.isEditMode;
        return cell;
    }else if (self.state == CUSTOMER_LATENT)//潜在客户
    {
        static NSString *ID = @"latentCustomercell";
        LatentCustomerCCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell)
        {
            cell = [[LatentCustomerCCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            [cell initWithTableView:mainTableView withModel:[dataArray objectAtIndex:indexPath.row]];
        }
        
        
        cell.btnDelegate = self;
        cell.model = [dataArray objectAtIndex:indexPath.row];
        return cell;
    }
    
    return nil;
}

-(void)cellOnClick:(UIButton*)sender{
    
    if (!self.isEditMode) {
        return;
    }
    
    CustomerModel *data = [dataArray objectAtIndex:sender.tag];
    
    [data setIsSelected:!data.isSelected];
    
    [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:sender.tag inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    
    if ([data isSelected]==false) {
        
        [[footerView selectAllBtn] setHighlighted:false];
        [footerView setIsSelectedAllFlag:false];
    }
    
}

-(void)btnOnClick:(UIButton *)btn
{
    if (btn.tag == 56) {
        [self refreshData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    if (dataArray&&dataArray.count>0)
    {
        
        return [RealCustomerCell getHeight];
    }
    
    return  mainTableView.frame.size.height;
}

-(void)myCustomerVcBtnClicked:(UIButton *)sender
{
    
    if (sender==actionTitleView.abackBtn) {
        [self.nav popViewControllerAnimated:YES];
        
    }else if (sender==actionTitleView.aaddBtn){//添加真实客户
        
        if ( !actionTitleView.aeditBtn.hidden) {
            AddRealCustomerVC *vc = [AddRealCustomerVC new];
            vc.nav = self.nav;
            vc.hidesBottomBarWhenPushed = YES;
            [self.nav pushViewController:vc animated:YES];
            
        }else//添加潜在客户
        {
            
            MiddleManAddCustomerViewController *vc = [[MiddleManAddCustomerViewController alloc]initWithNibName:@"MiddleManAddCustomerViewController" bundle:nil];
            vc.nav = self.nav;
            vc.hidesBottomBarWhenPushed = YES;
            [self.nav pushViewController:vc animated:YES];;
            
        }
        
    }else if (sender==actionTitleView.aeditBtn){
        
        if(!(dataArray.count == 0) && !(dataArray == nil))
        {
            [self.seachField resignFirstResponder];
            
            [seachView hide];
            
            self.isEditMode = !self.isEditMode;
            
            [self.mainTableView reloadData];
            
            if (self.isEditMode) {
                [footerView setHidden:false];
            }else{
                [footerView setHidden:YES];
            }
        }
    }
}



#pragma mark realCustomercell的代理（绑定楼盘）
-(void)realCustomerCellDidClickBingPremisesWithCustomerId:(NSString *)consumerId withConsumerCode:(NSString *)userCode
{
    BingPremiseVc *vc = [[BingPremiseVc alloc]initWithNibName:@"BingPremiseVc" bundle:nil];
    vc.vcState = PREVIOUSVC_LATENVC;
    vc.coustomerId = consumerId;
    vc.coustomerCode = userCode;
    vc.hidesBottomBarWhenPushed = YES;
    [self.nav pushViewController:vc animated:YES];
}
#pragma mark realCustomerCell的代理（点击了禁用，启用按钮）
-(void)realCustomerCellDidClickForbiddenBtnWithCustomerId:(NSString *)consumerId withStauts:(NSString *)stauts
{
    
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *userId = [NSString stringWithFormat:@"%zd",[UserModal shareUserModel].userId];
        NSString *customerStats = [stauts isEqualToString:@"0"]?@"1":@"0";
        ResulteMod *mod =  [_dataMange modifyconsumerstatusWithBrokerId:userId withcConsumerId:consumerId withStatus:customerStats];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:bself.view];
            
            if (mod.resltState == ResultFail)
            {
                [MBProgressHUD showError:mod.resultTip];
            }else if(mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                [MBProgressHUD showSuccess:@"操作成功"];
            }
            [bself refreshData];
            
        });
    });
}

#pragma mark latentCustomerCell的代理（转为真实客户)
-(void)LatentCustomerCCellDidClickpotentialchangtorealWithModel:(CustomerModel *)model withCell:(LatentCustomerCCell *)cell
{
    AddRealCustomerVC *vc = [AddRealCustomerVC new];
    vc.latenModel = model;
    vc.nav = self.nav;
    vc.cell = cell;
    vc.state = isLanteToRealCustomer;
    vc.hidesBottomBarWhenPushed = YES;
    [self.nav pushViewController:vc animated:YES];
}
#pragma mark latentCustomerCell的代理（锁定客户)
-(void)LatentCustomerCCellDidClickLockBtnWithPotentialId:(NSString *)potentialId withCell:(LatentCustomerCCell *)cell
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    
    __weak typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *customerId = [NSString stringWithFormat:@"%zd",[UserModal shareUserModel].userId];
        ResulteMod *mod = [bself.dataMange lockpotentiallWithConsumerId:customerId withPotentialId:potentialId];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];
            }else if(mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:[NSString stringWithFormat:@"网络错误"] toView:bself.view];
            }else
            {
                [MBProgressHUD showSuccess:@"客户锁定成功" toView:bself.view];
                cell.customerView.tipLab.hidden = YES;
                
                
            }
            [bself refreshData];
            
        });
    });
    
}
#pragma mark latentCustomerCell的代理（编辑客户－－潜在客户)
-(void)LatentCustomerCCellDidClickEditBtnWithModel:(CustomerModel *)model
{
    MiddleManAddCustomerViewController *vc = [[MiddleManAddCustomerViewController alloc]initWithNibName:@"MiddleManAddCustomerViewController" bundle:nil];
    vc.nav = self.nav;
    vc.custModel = model;
    vc.state = vcState_edit;
    vc.hidesBottomBarWhenPushed = YES;
    [self.nav pushViewController:vc animated:YES];
    
}


#pragma mark realCustoemrCell的代理（编辑客户－－－真实客户)
-(void)realCustomerCellDidClickEditBtnWithCustomerModel:(CustomerModel *)model
{
    EditRealCustomerVc *vc = [[EditRealCustomerVc alloc]initWithNibName:@"EditRealCustomerVc" bundle:nil];
    vc.customerModel = model;
    vc.hidesBottomBarWhenPushed = YES;
    [self.nav pushViewController:vc animated:YES];
}

#pragma mark seachView delegate
-(NSArray*)getDataByKewWord:(NSString*)kewWord{
    
    return seachArray;
}


-(CGFloat)getCellHight{
    
    return 60;
}

-(NSInteger)getCellCount{
    
    return seachArray.count;
}

-(UITableViewCell*)getCellByTableView:(UITableView *)tableView WithIndexPath:(NSIndexPath *)indexPath{
    
    if (self.state == CUSTOMER_TURE) {//真实客户
        static NSString *ID = @"realCustomerCell";
        RealCustomerCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil)
        {
            cell = [[RealCustomerCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            
            [cell cellWithTableView:seachView.tableView];
        }
        cell.btnDelegate = self;
        
        cell.model = [seachArray objectAtIndex:indexPath.row];
        return cell;
    }else if (self.state == CUSTOMER_LATENT)//潜在客户
    {
        static NSString *ID = @"latentCustomercell";
        LatentCustomerCCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell)
        {
            cell = [[LatentCustomerCCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            [cell initWithTableView:seachView.tableView withModel:[seachArray  objectAtIndex:indexPath.row]];
        }
        cell.btnDelegate = self;
        cell.model = [seachArray  objectAtIndex:indexPath.row];
        return cell;
    }
    
    return nil;
    
}

-(void)didSelecteItemIndex:(int)index{
    
    
}

-(void)hideSearchView
{
    
    self.seachField.text = @"";
    isSeachType = NO;
    seachArray = nil;
    
    
    [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
    self.cacelBtn.enabled = NO;
}

#pragma mark textField delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [self.seachView show];
    
    [self.seachView tableViewReloadAndUpFrame];
    [self.cacelBtn setTitle:@"取消" forState:UIControlStateNormal];
    self.cacelBtn.enabled = YES;
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    self.seachField.text = @"";
    [textField resignFirstResponder];
    [self.seachView hide];
    isSeachType = NO;
    seachArray = nil;
    
    [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
    self.cacelBtn.enabled = NO;
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    NSMutableString *keyStr = [NSMutableString stringWithString:textField.text];
    
    if(![StringTool isBlankString:string])
    {
        [keyStr appendString:string];
    }else
    {
        NSUInteger length = keyStr.length - 1;
        
        NSRange rang =  NSMakeRange(0, length);
        
        keyStr =  [NSMutableString stringWithString:[keyStr substringWithRange:rang]];
    }
    
    keyWord = keyStr;
    
    keyWord = keyStr.length >0? keyStr:@"???????";
    if(keyWord.length >= 2)
    {
        isSeachType = YES;
        [self searchRefreshData];
        
        [self.seachView tableViewReloadAndUpFrame];
    }
    
    return true;
}


#pragma mark footerMuenVIew的代理(全选）
-(void)footerMenuViewSelectAllBtnOnClicked
{
    self.isSeletedAll = !self.isSeletedAll;
    NSMutableArray *arrM = [[NSMutableArray alloc]init];
    for (CustomerModel *model in dataArray) {
        model.isSelected = self.isSeletedAll;
        [arrM addObject:model];
    }
    self.dataArray = [[NSArray alloc]initWithArray:arrM];
    [self.mainTableView reloadData];
}

#pragma mark footerMuenVIew的代理(禁用）
-(void)footerMenuViewbeUnAbleBtnOnClicked
{
    if ([[self getSeletedCustomerIds] isEqualToString:@"NO"]) {
        [MBProgressHUD showError:@"请至少选择一个客户"];
        return;
    }
    
    [self updateMultiOperateWithStauts:@"1"];
    self.isClickAbleBtn = -1;
}

#pragma mark footerMuenVIew的代理(启用）
-(void)footerMenuViewBeAbleBtnOnClicked
{
    if ([[self getSeletedCustomerIds] isEqualToString:@"NO"]) {
        [MBProgressHUD showError:@"请至少选择一个客户"];
        return;
    }
    
    [self updateMultiOperateWithStauts:@"0"];
    self.isClickAbleBtn = 1;
    
}


#pragma mark 获取被选中的客户的ID
-(NSString *)getSeletedCustomerIds
{
    NSMutableArray *idArrM = [NSMutableArray array];
    
    
    for (CustomerModel  *model in dataArray) {
        
        if (model.isSelected) {
            [idArrM addObject:model.consumerId];
        }
    }
    if (idArrM.count == 0) {
        return @"NO";
    }
    return [idArrM componentsJoinedByString:@","];
}

#pragma mark 批量操作提交数据,staut 0:表示要启用操作，1表示要禁用操作
-(void)updateMultiOperateWithStauts:(NSString *)stauts
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *customerId = [NSString stringWithFormat:@"%zd",[UserModal shareUserModel].userId];
        ResulteMod *mod = [bself.dataMange batchmodifystatusWithCustoemrIds:[bself getSeletedCustomerIds] WithcustomerId:customerId WithStatus:stauts];
        
        sleep(1);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            [bself.footerView.selectAllBtn setImage:[UIImage imageNamed:@"fuxuan_birder"] forState:UIControlStateNormal];
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                [MBProgressHUD showSuccess:@"保存成功"];
                
                [bself refreshData];
            }
            
            
        });
    });
}
- (IBAction)clickCancelBtn:(id)sender {
    
    [self.seacrTv setText:@""];
    self.keyWord = @"**********";
    
    [self.seacrTv resignFirstResponder];
    [self.seacrTv textDicChange:@""];;
    [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
    self.cacelBtn.enabled = NO;
    self.seachArray = nil;
    
    
    [self.seachView hide];
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
{
    if (dataArray.count == 0 ||dataArray == nil) {
        return YES;
    }
    
    [self.seacrTv textDicChange:@""];
    
    [self.cacelBtn setTitle:@"取消" forState:UIControlStateNormal];
    self.cacelBtn.enabled = YES;
    
    [self.seachView show];
    
    [self.seachView tableViewReloadAndUpFrame];
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView;
{
    [self.seacrTv textDicChange:textView.text];
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimedString = [textView.text stringByTrimmingCharactersInSet:set];
    
    self.keyWord = textView.text;
    if (trimedString.length == 0) {
        self.keyWord = @"***********";
        
    }
    [self searchRefreshData];
    [self.seachView tableViewReloadAndUpFrame];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        [self.seacrTv setText:@""];;
        [self.seacrTv textDicChange:@""];
        [self.seachView hide];
        self.seachArray = nil;
        
        [self.cacelBtn setTitle:@"" forState:UIControlStateNormal];
        self.cacelBtn.enabled = NO;
        
        ;
    }
    self.keyWord = @"***********";
    return YES;
}
#pragma mark menuScroTableView delegate

-(void)cellMenDidHide:(UITableView*)tableView  cell:(ScroDeleteCell*)cell{
    
    if (!actionTitleView.aeditBtn.hidden) {
        RealCustomerCell *realCell = (RealCustomerCell *)cell;
        [realCell.customerView.rightBtn setImage:[UIImage imageNamed:@"right_back_shift"] forState:UIControlStateNormal];
        return;
    }
    LatentCustomerCCell *latentCell = (LatentCustomerCCell *)cell;
    [latentCell.customerView.rightBtn setImage:[UIImage imageNamed:@"right_back_shift"] forState:UIControlStateNormal];
}


-(void)cellMenDidShow:(UITableView*)tableView cell:(ScroDeleteCell*)cell{
    
    if (!actionTitleView.aeditBtn.hidden) {
        RealCustomerCell *realCell = (RealCustomerCell *)cell;
        [realCell.customerView.rightBtn setImage:[UIImage imageNamed:@"right_jiantou2"] forState:UIControlStateNormal];
        return;
    }
    
    LatentCustomerCCell *latentCell = (LatentCustomerCCell *)cell;
    [latentCell.customerView.rightBtn setImage:[UIImage imageNamed:@"right_jiantou2"] forState:UIControlStateNormal];
    
    
}


@end
